<template>
    <div class="search-box">
        <div ref="searchContainer" class="search-container" :class="{ 'expanded': isExpanded }">
            <!-- 搜索图标 -->
            <div class="search-icon" @click="toggleSearch" :title="'搜索'">
                <i v-html="SEARCH_ICON" class="search-icon__svg"></i>
            </div>

            <!-- 搜索输入框 -->
            <input ref="searchInput" v-model="searchQuery" type="text" class="search-input" placeholder="搜索要访问的功能/数据"
                @focus="handleSearchFocus" @keyup.esc="closeSearch" />
            <!-- 关闭按钮 -->
            <div v-if="isExpanded" class="close-icon" @click="handleClearSearch" title="关闭">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                        stroke-linejoin="round" />
                </svg>
            </div>

            <!-- 搜索结果下拉框 -->
            <div v-show="showSearchResults && isExpanded" class="search-results" @mouseenter="handleResultsMouseEnter"
                @mouseleave="handleResultsMouseLeave">
                <!-- 搜索历史 -->
                <div v-if="searchHistory.length > 0" class="search-history">
                    <div v-for="(historyItem, index) in searchHistory" :key="index" class="search-history-item"
                        @click="handleHistoryClick(historyItem)">
                        <div class="history-name" :title="historyItem">{{ historyItem }}</div>
                        <div class="icon-t-Close" @click.stop="removeHistoryItem(index)" title="删除"></div>
                    </div>
                </div>
                <!-- 搜索结果 -->
                <div v-if="searchQuery.trim() || searchResults.length > 0" class="search-results-content" :style="{padding: searchResults.length > 0 ? '16px 28px' : '0'}">
                    <div v-if="searchResults.length === 0 && !isSearching" class="search-no-results">
                        未找到和【{{ searchQuery }}】相关的功能/数据，请尝试其他关键字
                    </div>
                    <div style="display: flex;" v-if="searchResults.length > 0">
                        <span class="search-results-content_title">功能（{{searchResults.reduce((total, app) => total +
                            app.FunctionList.length, 0)}}）</span>
                        <div class="search-results-content_line"></div>
                    </div>
                    <div class="search-results-content_data" v-if="searchResults.length > 0">
                        <div v-for="app in searchResults" :key="app.ApplicationID" class="search-app-group">
                            <div class="app-header">
                                <span class="app-name">{{ app.ApplicationName }}</span>
                                <span
                                    v-if="app.FunctionList.length > DEFAULT_DISPLAY_COUNT && !expandedApps.has(app.ApplicationID)"
                                    class="more-button" @click.stop="toggleAppExpansion(app.ApplicationID)">查看更多</span>
                                <span v-if="expandedApps.has(app.ApplicationID)" class="more-button"
                                    @click.stop="toggleAppExpansion(app.ApplicationID)">收起更多</span>
                            </div>
                            <div class="function-list">
                                <div v-for="(func, index) in (expandedApps.has(app.ApplicationID) ? app.FunctionList : app.FunctionList.slice(0, DEFAULT_DISPLAY_COUNT))"
                                    :key="func.ID" class="search-result-item" @click="handleResultClick(func)">
                                    <i :class="func.Icon || DEFAULT_FUNCTION_ICON" class="func-icon"></i>
                                    <div class="result-name" v-html="getHighlightedName(func.Name)"></div>
                                    <Popover position="rightTop" trigger="click" ref="popoverRefs" 
                                    :offset="[0, 2]" customClass="func-info-popover" :stopPropagation="true"  @after-enter="(event) => afterEnter(event, func.ID)" @after-leave="afterLeave">
                                        <template v-slot:reference>
                                            <i v-html="MENU_INFO_MOVE_ICON" :id="func.ID + '_more'"
                                                class="menu-move_icon"></i>
                                        </template>
                                        <FuncInfoTag :funcId="func.ID" :funcName="func.Name" @close-popover="handleClosePopover(func.ID)" />
                                    </Popover>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { searchFunctions } from '@/service/funcMenuService'
import { SEARCH_ICON, DEFAULT_FUNCTION_ICON } from '@/constants/svg'
import { eventBus } from '@/service/eventService'
import userProfileService from '@/service/userProfileService'
import { highlightKeyword } from '@/service/commonService'
import { MENU_INFO_MOVE_ICON } from '@/constants/svg.js'
import FuncInfoTag from '@/components/pc/FuncInfoTag.vue'
import Popover from '@/components/common/Popover.vue'

const emit = defineEmits(['search-result-click'])


const searchQuery = ref('')

const isExpanded = ref(false)
const searchInput = ref(null)
const searchContainer = ref(null)
const searchHistory = ref([])
const isMouseInResults = ref(false)
const searchResults = ref([])
const expandedApps = ref(new Set()) // 跟踪展开的应用
const popoverRefs = ref([]) // Popover引用
const isSearching = ref(false) // 搜索状态标识

// 常量定义
const DEFAULT_DISPLAY_COUNT = 6 // 默认显示的功能数量

// 生成高亮的功能名称
const getHighlightedName = (name) => {
    if (!searchQuery.value.trim()) {
        return name
    }
    return highlightKeyword(name, searchQuery.value.trim(), 'search-highlight')
}

// 搜索功能菜单
const performSearch = async (keyword) => {
    try {
        if (!keyword || !keyword.trim()) {
            searchResults.value = []
            expandedApps.value.clear()
            isSearching.value = false
            return
        }
        
        isSearching.value = true
        const results = await searchFunctions(keyword)
        searchResults.value = results
        // 重置展开状态
        expandedApps.value.clear()
        isSearching.value = false
    } catch (error) {
        console.error('搜索功能菜单失败:', error)
        searchResults.value = []
        expandedApps.value.clear()
        isSearching.value = false
    }
}

// 切换应用展开状态
const toggleAppExpansion = (applicationId) => {
    if (expandedApps.value.has(applicationId)) {
        expandedApps.value.delete(applicationId)
    } else {
        expandedApps.value.add(applicationId)
    }
}

// 搜索相关方法
const toggleSearch = async () => {
    isExpanded.value = !isExpanded.value
    if (isExpanded.value) {
        await nextTick()
        searchInput.value?.focus()
    } else {
        searchQuery.value = ''
    }
}
const showSearchResults = computed(() => {
    return isExpanded.value && (searchQuery.value.trim().length > 0 || searchHistory.value.length > 0)
})

const closeSearch = () => {
    // 如果有输入内容，保存到搜索历史
    
    const query = searchQuery.value.trim()
    if (query) {
        saveSearchKeywordToHistory(query)
    }

    isExpanded.value = false
    searchQuery.value = ''
}

watch(searchQuery, (newValue, oldValue) => {
    if (newValue !== oldValue) {
        handleSearchInput()
    }
})
const handleSearchInput = async () => {
    // 如果搜索内容为空，加载搜索历史；否则执行搜索
    if (searchQuery.value.trim().length === 0) {
        loadSearchHistory()
        searchResults.value = []
        isSearching.value = false
    } else {
        await performSearch(searchQuery.value)
    }
}


const handleSearchFocus = () => {
    if (searchQuery.value.trim().length === 0) {
        loadSearchHistory()
        searchResults.value = []
    }
}


const handleResultsMouseEnter = () => {
    isMouseInResults.value = true
}

const handleResultsMouseLeave = () => {
    isMouseInResults.value = false
}

const handleResultClick = (result) => {
    emit('search-result-click', result)
    closeSearch()
}

// 搜索历史相关方法
const loadSearchHistory = () => {
    try {
        const history = userProfileService.getUserProfile('wrp_searchHistory')
        if (history) {
            searchHistory.value = history
        } else {
            searchHistory.value = []
        }
    } catch (error) {
        console.error('加载搜索历史失败:', error)
        searchHistory.value = []
    }
}



const removeHistoryItem = (index) => {
    searchHistory.value.splice(index, 1)
    userProfileService.saveUserProfile('wrp_searchHistory', searchHistory.value)
    // 删除后重新聚焦到输入框，防止下拉框关闭
    nextTick(() => {
        if (searchInput.value) {
            searchInput.value.focus()
        }
    })
}

const handleHistoryClick = (historyItem) => {
    searchQuery.value = historyItem
}

const handleClearSearch = () => {
    searchQuery.value = ''
    nextTick(() => {
        searchInput.value?.focus()
    })
}

const calculateMaxHistoryCount = () => {
    // 基础配置
    const containerWidth = window.innerWidth * 0.33 // 33vw
    const itemPadding = 20 // 每项左右padding 10px * 2
    const itemGap = 8 // 项目间距
    const deleteIconWidth = 24 // 删除图标宽度(包含gap)
    const containerPadding = 56 // 容器左右padding 28px * 2

    // 计算可用宽度
    const availableWidth = containerWidth - containerPadding

    // 估算平均字符宽度(中文约14px，英文约8px)
    const avgCharWidth = 11

    // 计算当前历史记录的总宽度
    let totalWidth = 0
    let count = 0

    for (const item of searchHistory.value) {
        const itemText = typeof item === 'string' ? item : item.Name || ''
        const textWidth = itemText.length * avgCharWidth
        const itemWidth = textWidth + itemPadding + deleteIconWidth + itemGap

        if (totalWidth + itemWidth > availableWidth) {
            break
        }

        totalWidth += itemWidth
        count++
    }

    // 至少保留3个，最多15个
    return Math.max(3, Math.min(count || 8, 15))
}

const saveSearchKeywordToHistory = (keyword) => {
    if (!keyword || !keyword.trim()) return

    const trimmedKeyword = keyword.trim()

    // 移除重复项（如果存在）
    const existingIndex = searchHistory.value.findIndex(item =>
        typeof item === 'string' ? item === trimmedKeyword : item.Name === trimmedKeyword
    )

    if (existingIndex !== -1) {
        searchHistory.value.splice(existingIndex, 1)
    }

    // 添加到开头
    searchHistory.value.unshift(trimmedKeyword)

    // 动态限制历史记录数量，考虑字符长度和容器宽度
    const maxHistoryCount = calculateMaxHistoryCount()
    if (searchHistory.value.length > maxHistoryCount) {
        searchHistory.value = searchHistory.value.slice(0, maxHistoryCount)
    }

    try {
        userProfileService.saveUserProfile('wrp_searchHistory', searchHistory.value)
    } catch (error) {
        console.error('保存搜索历史失败:', error)
    }
}

const initEventListeners = () => {
    eventBus.on('iframeClickEvent', () => {
        closeSearch()
    })

    // 添加点击外部区域关闭搜索的事件监听器
    const handleClickOutside = (event) => {
        if (isExpanded.value && searchContainer.value && !searchContainer.value.contains(event.target)) {
            // 检查是否点击了搜索结果区域
            const searchResultsElement = document.querySelector('.search-results')
            if (searchResultsElement && searchResultsElement.contains(event.target)) {

                return // 点击搜索结果区域不关闭
            }
            closeSearch()
        }
    }

    document.addEventListener('click', handleClickOutside)

    // 存储事件处理器以便后续移除
    window._searchBoxClickHandler = handleClickOutside
}

// Popover相关方法
const afterEnter = async (event, funcId) => {
    // 先关闭所有其他已打开的Popover
    popoverRefs.value.forEach((popover, index) => {
        if (popover && popover.closePopover) {
            const currentFuncId = searchResults.value
                .flatMap(app => app.FunctionList || [])[index]?.ID
            if (currentFuncId !== funcId) {
                popover.closePopover()
            }
        }
    })
    
    // 通过 funcId 找到对应的 popover 元素
    let popoverBody = document.querySelector(`.func-info-popover`)
    if (!popoverBody) return

    // 找到对应的 popover 引用
    const popoverIndex = searchResults.value
        .flatMap(app => app.FunctionList || [])
        .findIndex(func => func.ID === funcId)

    if (popoverIndex === -1) return

    const handleMouseLeave = () => {
        setTimeout(() => {
            if (!popoverBody.matches(':hover')) {
                // 只关闭当前的Popover
                const currentPopover = popoverRefs.value[popoverIndex]
                if (currentPopover && currentPopover.closePopover) {
                    currentPopover.closePopover()
                }
            }
        }, 100)
    }
    await nextTick()
    popoverBody = document.querySelector(`.func-info-popover`)
    popoverBody.addEventListener('mouseleave', handleMouseLeave)
    // 存储事件处理器以便后续移除
    popoverBody._mouseLeaveHandler = handleMouseLeave
    popoverBody._funcId = funcId // 存储 funcId 用于后续清理
}

const afterLeave = () => {
    // Popover关闭后，移除事件监听器
    const popoverBody = document.querySelector('.func-info-popover')
    if (popoverBody && popoverBody._mouseLeaveHandler) {
        popoverBody.removeEventListener('mouseleave', popoverBody._mouseLeaveHandler)
        delete popoverBody._mouseLeaveHandler
        delete popoverBody._funcId
    }
}

const handleClosePopover = (funcId) => {
    // 找到对应的 popover 引用索引
    const popoverIndex = searchResults.value
        .flatMap(app => app.FunctionList || [])
        .findIndex(func => func.ID === funcId)

    if (popoverIndex !== -1) {
        const currentPopover = popoverRefs.value[popoverIndex]
        if (currentPopover && currentPopover.closePopover) {
            currentPopover.closePopover()
        }
    }
}

const closeAllPopovers = () => {
    popoverRefs.value.forEach(popover => {
        if (popover && popover.closePopover) {
            popover.closePopover()
        }
    })
}


// 组件挂载时获取所有功能菜单
onMounted(async () => {
    initEventListeners()
    loadSearchHistory()
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
    if (window._searchBoxClickHandler) {
        document.removeEventListener('click', window._searchBoxClickHandler)
        delete window._searchBoxClickHandler
    }
})

defineExpose({
    closeAllPopovers
})
</script>
<style lang="scss">
/* 搜索关键词高亮样式 */
.search-highlight {
    background-color: #FFBB29;
}
.custom-popover-body.func-info-popover{
    z-index: 1000;
}
</style>
<style scoped lang="scss">
.menu-move_icon {
    display: none;
    /* 默认隐藏图标 */
    width: 14px;
    height: 14px;
}

.search-results-content_data {
    padding-top: 16px;
}

.search-icon__svg {
    width: 16px;
    height: 16px;
}

.search-box {
    position: relative;
}

.search-container {
    position: relative;
    display: flex;
    align-items: center;
    width: 36px;
    height: 36px;
    transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: visible;
}

.search-container.expanded {
    width: 33vw;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
}

.search-container.expanded:focus-within {
    border-color: var(--theme-color);
    background-color: #fff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.search-icon {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    z-index: 2;
    transition: color 0.2s ease;
}

.search-results-content {

}

.search-icon:hover {
    color: var(--theme-color);
}

.search-input {
    width: 100%;
    height: 34px;
    padding: 0 40px 0 40px;
    border: none;
    background: transparent;
    font-size: 14px;
    outline: none;
    opacity: 0;
    transition: opacity 0.2s ease 0.1s;
}

.search-container.expanded .search-input {
    opacity: 1;
}

.search-input::placeholder {
    color: transparent !important;
}

.search-container.expanded .search-input::placeholder {
    color: #999999 !important;
}

.search-results-content_title {
    font-size: 14px;
    color: #262626;
    font-weight: 700;
}

.search-results-content_line {
    width: calc(100% - 150px);
    margin: 10px 0 0 20px;
    height: 1px;
    background-color: #f1f1f1;
}

.history-name {
    white-space: nowrap;
    color: #333;
}

.close-icon {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    z-index: 2;
    transition: color 0.2s ease;
}

.close-icon:hover {
    color: #666;
}

/* 搜索结果下拉框 */
.search-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 4px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
    z-index: 1001;
    margin-top: 4px;
    overflow-x: hidden;
    max-height: 600px;
}



.history-title {
    font-size: 12px;
    color: #666;
    font-weight: 500;
}


.search-history {
    display: flex;
    gap: 8px;
    overflow: hidden;
    padding: 10px 28px;
}

.search-history-item {
    height: 24px;
    cursor: pointer;
    min-width: 10px;
    line-height: 24px;
    padding: 0 10px;
    background: #f1f1f1;
    border-radius: 12px;
    color: #333;
    font-size: 14px;
    flex-wrap: nowrap;
    display: flex;
    align-items: center;
    gap: 12px;

    .icon-t-Close {
        font-size: 12px;
    }
}


.search-history-item:hover {
    background: #d1d0d0;
}



.search-no-results {
    padding: 10px 28px;
    color: #606266;
    text-align: left;
    font-size: 14px;
}


.result-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 2px;
}

.result-group {
    font-size: 12px;
    color: #999;
}

/* 应用分组样式 */
.search-app-group {
    margin-bottom: 16px;
}

.search-app-group:last-child {
    margin-bottom: 0;
}

.app-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
}

.app-name {

    font-size: 14px;
    font-weight: 700;
    color: rgba(0, 0, 0, .56);
}

.more-button {
    font-size: 14px;
    color: var(--theme-color);
    cursor: pointer;
    user-select: none;
    transition: color 0.2s ease;
}


.function-list {
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
}

.function-list .search-result-item {
    width: 270px;
    margin: 7px 0 8px;
    padding: 7px 20px 8px;
    gap: 8px;
    line-height: 25px;
    cursor: pointer;
    display: flex;
    align-items: center;

    &:hover {
        border-radius: 5px;
        background-color: var(--theme-color-background);
    }

    .result-name {
        color: rgb(38, 38, 38);
        display: flex;
    }

    .func-icon {
        position: relative;
        bottom: 1.5px;
        color: var(--theme-color);
    }

    .custom-popover-reference--visible {
        .menu-move_icon {
            display: block;
        }
    }

    &:hover .menu-move_icon {
        display: block;
    }

    .custom-popover {
        margin-left: auto;
    }
}
</style>